<?php


namespace App\Http\Controllers\WebApi;


use App\Http\Controllers\WebApi\Business\ConfigBusiness;
use App\Http\Controllers\WebApi\Business\OperationLogsBusiness;
use App\Jobs\RegisterTask;
use App\Models\ImAddressBook;
use App\Models\ImInviteCode;
use App\Models\ImOperationLogs;
use App\Models\ImUserFriend;
use App\Models\ImUsers;
use App\Models\User;
use App\Services\Huanxin\ChatServices;
use App\Services\Huanxin\UserServices;
use App\Validators\AuthValidator;
use App\Validators\UserValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController
{
    /**
     * 用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userList(Request $request)
    {
        $param = $request->all();
        list($offset, $limit, $page, $pagesize) = ImUsers::pageProcess();
        $query = ImUsers::with(['lastLoginLog']);
        $calc = ImUsers::selectRaw('count(*) as total')->selectRaw('sum( if(users.online=1,1,0) ) as onlineNums');
        $calc->selectRaw('sum(im_user_balance.money) as balance')->selectRaw('sum(if(im_user_balance.status=0,im_user_balance.money,0)) as freeze')->leftJoin('im_user_balance', 'users.id', '=', 'im_user_balance.user_id');
        //用户昵称、手机号、ID搜索
        if (isset($param['searchWord'])) {
            $query->where(function ($sql) use ($param) {
                $sql->where('users.id', $param['searchWord']);
                $sql->orWhere('users.nickname', $param['searchWord']);
                $sql->orWhere('users.phone', $param['searchWord']);
            });
            $calc->where(function ($sql) use ($param) {
                $sql->where('users.id', $param['searchWord']);
                $sql->orWhere('users.nickname', $param['searchWord']);
                $sql->orWhere('users.phone', $param['searchWord']);
            });
        }
        //是否在线
        if (isset($param['online']) && is_numeric($param['online'])) {
            $query->where('users.online', $param['online']);
            $calc->where('users.online', $param['online']);
        }
        //是否机器人
        if (isset($param['isRobot']) && $param['isRobot'] > 0) {
            $query->where('users.user_type', 1);
            $calc->where('users.user_type', 1);
        }
        //ip搜索
        if (!empty($param['ip'])) {
            $query->whereHas('lastLoginLog', function ($sql) use ($param) {
                $sql->select('id')->where('ip', $param['ip']);
            });
            $calc->whereHas('lastLoginLog', function ($sql) use ($param) {
                $sql->select('id')->where('ip', $param['ip']);
            });
        }
        //是否实名认证
        if (isset($param['auth_status']) && is_numeric($param['auth_status'])) {
            $query->where('users.auth_status', $param['auth_status']);
            $calc->where('users.auth_status', $param['auth_status']);
        }
        //注册、最后上线、最后离线时间搜索
        if (isset($param['timeType']) && !empty($param['timeStart']) && !empty($param['timeEnd'])) {
            switch ($param['timeType']) {
                case 'regTime':
                    $query->whereBetween('users.created_at', [$param['timeStart'], $param['timeEnd']]);
                    $calc->whereBetween('users.created_at', [$param['timeStart'], $param['timeEnd']]);
                    break;
                case 'loginTime':
                    $query->whereHas('lastLoginLog', function ($sql) use ($param) {
                        $sql->select('id')->whereBetween('created_at', [$param['timeStart'], $param['timeEnd']]);
                    });
                    $calc->whereHas('lastLoginLog', function ($sql) use ($param) {
                        $sql->select('id')->whereBetween('created_at', [$param['timeStart'], $param['timeEnd']]);
                    });
                    break;
                case 'logoutTime':
                    $query->whereHas('lastLoginLog', function ($sql) use ($param) {
                        $sql->select('id')->whereBetween('logouted_at', [$param['timeStart'], $param['timeEnd']]);
                    });
                    $calc->whereHas('lastLoginLog', function ($sql) use ($param) {
                        $sql->select('id')->whereBetween('logouted_at', [$param['timeStart'], $param['timeEnd']]);
                    });
                    break;
            }
        }
        //是否短信认证
        if (isset($param['sms_auth']) && is_numeric($param['sms_auth'])) {
            $query->where('users.sms_auth', $param['sms_auth']);
            $calc->where('users.sms_auth', $param['sms_auth']);
        }
        //用户状态, 0封禁 1正常
        if (isset($param['status']) && is_numeric($param['status'])) {
            $query->where('users.status', $param['status']);
            $calc->where('users.status', $param['status']);
        }
        $summary = $calc->first();
        $summary->onlineNums = intval($summary->onlineNums);
        $summary->balance = floatval($summary->balance);
        $summary->freeze = floatval($summary->freeze);
        $summary->page = $page;
        $summary->pagesize = $pagesize;
        $query->select(['id', 'user_type', 'nickname', 'sex', 'headimg', 'realname', 'personalized_signature',
            'easemob_id', 'area_code', 'phone', 'auth_status', 'status', 'im_number', 'sms_auth', 'online', 'created_at', 'updated_at']);
        if (isset($param['export']) && $param['export'] == 1) {
            //导出用户
            $data = $query->limit(5000)->get();
            return okBack($data);
        }
        $data = $query->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        return okBack($data, [
            'summary' => $summary
        ]);
    }

    /**
     * 编辑用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userEdit(Request $request)
    {
        $param = $request->all();
        $valid = UserValidator::handle($param, 'userEdit');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        $user = ImUsers::find($param['id']);
        $oldNickname = $user->nickname;
        if (!$user) {
            return errBack('用户不存在');
        }
        $user->nickname = $param['nickname'];
        $user->phone = $param['phone'];
        $user->sex = $param['sex'];
        if (isset($param['birthday'])) {
            $user->birthday = $param['birthday'];
        }
        $user->save();
        //添加操作日志
        if ($oldNickname != $param['nickname']) {
            OperationLogsBusiness::addLog(ImOperationLogs::UPDATE, '编辑用户;参数:' . json_encode($param, JSON_UNESCAPED_UNICODE));
        }
        return okBack();
    }


    /**
     * 重置用户密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPassword(Request $request)
    {
        $param = $request->all();
        $valid = AuthValidator::handle($param, 'resetPassword');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        if ($param['password'] != $param['confirm_password']) {
            return errBack('两次密码输入不一致');
        }
        $user = ImUsers::find($param['id']);
        if (!$user) {
            return errBack('用户不存在');
        }
        $user->password = bcrypt(md5($param['password']));
        $user->save();
        return okBack();
    }

    /**
     * 添加用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userAdd(Request $request)
    {
        $param = $request->all();
        $valid = AuthValidator::handle($param, 'userAdd');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        $count = ImUsers::where('phone', $param['phone'])->count();
        if ($count) {
            return errBack('手机号已被注册');
        }
        DB::beginTransaction();
        try {
            $user = new User();
            $user->nickname = $param['nickname'];
            $user->phone = $param['phone'];
            $user->password = Hash::make($param['password']);
            $user->sex = $param['sex'];
            $user->user_type = $param['user_type'];
            if (isset($param['birthday'])) {
                $user->birthday = $param['birthday'];
            }
            $user->save();
            // 加入到注册队列中
            RegisterTask::dispatch(['user_id' => $user->id]);
            //添加操作日志
            OperationLogsBusiness::addLog(ImOperationLogs::CREATE, '添加用户;ID:' . $user->id);
            DB::commit();
            return okBack();
        } catch (\Exception $e) {
            DB::rollBack();
            return errBack('添加失败');
        }
    }

    /**
     * 添加机器人
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function robotAdd(Request $request)
    {
        $param = $request->all();
        $valid = AuthValidator::handle($param, 'robotAdd');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        for ($i = 0; $i < $param['nums']; $i++) {
            $user = new ImUsers();
            $user->nickname = ConfigBusiness::nickname();
            $user->phone = 0;
            $user->password = Hash::make('6612359');
            $user->sex = mt_rand(1, 2);
            $user->user_type = 1;
            $user->save();
        }
        return okBack();
    }

    /**
     * 我的好友列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function myFriend(Request $request)
    {
        $user_id = $request->get('user_id');
        if ($user_id <= 0) {
            return errBack('用户信息有误');
        }
        $user = ImUsers::find($user_id);
        if (!$user) {
            return errBack('用户不存在');
        }
        list($offset, $limit, $page, $pagesize) = ImUserFriend::pageProcess();
        $myFriend = ImUserFriend::where('im_user_friend.user_id', $user_id)->join('users', 'im_user_friend.other_uid', '=', 'users.id');
        $total = $myFriend->count();
        $data = $myFriend->select(['users.id as friend_id', 'users.nickname', 'im_user_friend.status', 'im_user_friend.no_disturb', 'im_user_friend.created_at'])->offset($offset)->limit($limit)->orderBy('im_user_friend.id', 'desc')->get();
        return okBack($data, [
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize,
        ]);
    }

    /**
     * 通讯录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addressBook(Request $request)
    {
        $user_id = $request->get('user_id');
        if ($user_id <= 0) {
            return errBack('用户信息有误');
        }
        list($offset, $limit, $page, $pagesize) = ImUserFriend::pageProcess();
        $query = ImAddressBook::where('user_id', $user_id);
        $count = $query->count();
        $data = $query->select(['name', 'phone'])->offset($offset)->limit($limit)->get();
        return okBack($data, [
            'total' => $count,
            'page' => $page,
            'pagesize' => $pagesize
        ]);
    }

    /**
     * 生成邀请码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteCodeAdd(Request $request)
    {
        $nums = $request->post('nums');
        $user_id = $request->post('user_id');
        if ($nums <= 0 || $user_id <= 0) {
            return errBack('参数错误');
        }
        if ($nums > 2000) {
            return errBack('生成个数不能超过2000');
        }
        $data = [];
        for ($i = 0; $i < $nums; $i++) {
            array_push($data, [
                'code' => my_rand_str(),
                'user_id' => $user_id,
                'created_at' => time(),
                'updated_at' => time()
            ]);
        }
        $res = ImInviteCode::insert($data);
        //添加操作日志
        if ($res) {
            OperationLogsBusiness::addLog(ImOperationLogs::CREATE, '添加邀请码;数量:10;用户ID:' . $user_id);
        }
        return okBack();
    }

    /**
     * 删除邀请码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteCodeDel(Request $request)
    {
        $ids = $request->post('ids');
        $user_id = $request->post('user_id');
        $ids = json_decode($ids, true);
        if (empty($ids) || $user_id <= 0) {
            return errBack('参数错误');
        }
        $res = ImInviteCode::whereIn('id', $ids)->where('user_id', $user_id)->delete();
        //添加操作日志
        if ($res) {
            OperationLogsBusiness::addLog(ImOperationLogs::DELETE, '邀请码ID:' . join(',', $ids));
        }
        return okBack();
    }

    /**
     * 邀请码列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteCodeList(Request $request)
    {
        $user_id = $request->get('user_id');
        if ($user_id <= 0) {
            return errBack('参数错误');
        }
        list($offset, $limit, $page, $pagesize) = ImUserFriend::pageProcess();
        $query = ImInviteCode::where('user_id', $user_id);
        $code = $request->get('code');
        if (!empty($code)) {
            $query->where('code', $code);
        }
        $status = $request->get('status');
        if ($status > 0) {
            $query->where('status', $status);
        }
        $total = $query->count();
        $data = $query->offset($offset)->limit($limit)->get();
        return okBack($data, [
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize,
        ]);
    }

    /**
     * 删除用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userDel(Request $request)
    {
        $ids = $request->post('ids');
        $ids = json_decode($ids, true);
        if (empty($ids)) {
            return errBack('参数错误');
        }
        foreach ($ids as $val) {
            if ($val <= 0) {
                return errBack('参数错误');
            }
        }
        try {
            $res = ImUsers::destroy($ids);
            //添加操作日志
            if ($res) {
                OperationLogsBusiness::addLog(ImOperationLogs::DELETE, '删除用户;用户ID:' . join(',', $ids));
            }
            return okBack();
        } catch (\Exception $e) {
            return errBack();
        }
    }

    /**
     * 封禁用户
     * @param Request $request
     * $userIds 用户ID数组
     * $type 封禁时间
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-13 17:49
     */
    public function banned(Request $request)
    {
        $userIds = $request->post('userIds');
        $userIds = json_decode($userIds, true);
        if (empty($userIds)) {
            return errBack();
        }
        //oneDay threeDay fiveDay aWeek threeMonth sixMonth forever
        $type = $request->post('type');
        if (!in_array($type, ['oneDay', 'threeDay', 'fiveDay', 'aWeek', 'threeMonth', 'sixMonth', 'forever'])) {
            return errBack('时间类型有误');
        }
        $expire_at = 0;
        switch ($type) {
            case 'oneDay':
                $expire_at = strtotime('+1 day');
                break;
            case 'threeDay':
                $expire_at = strtotime('+3 day');
                break;
            case 'fiveDay':
                $expire_at = strtotime('+5 day');
                break;
            case 'aWeek':
                $expire_at = strtotime('+1 week');
                break;
            case 'threeMonth':
                $expire_at = strtotime('+3 month');
                break;
            case 'sixMonth':
                $expire_at = strtotime('+6 month');
                break;
            case 'forever':
                $expire_at = strtotime('+10 year');
                break;
            default:
                break;
        }
        ImUsers::whereIn('id', $userIds)->update([
            'expire_at' => $expire_at,
            'status' => 0,
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        return okBack();
    }

    /**
     * 解禁用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-13 17:57
     */
    public function unBanned(Request $request)
    {
        $userIds = $request->post('userIds');
        $userIds = json_decode($userIds, true);
        if (empty($userIds)) {
            return errBack();
        }
        ImUsers::whereIn('id', $userIds)->update([
            'status' => 1,
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        return okBack();
    }

    /**
     * 发送警告通知
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-13 18:38
     */
    public function sendWarning(Request $request)
    {
        $userId = $request->post('userId');
        $content = $request->post('content');
        if ($userId <= 0 || empty($content)) {
            return errBack();
        }
        $target_type = 'users';
        $ChatServices = new ChatServices();
        $result = $ChatServices->sendText($target_type, $userId, $content, '系统通知', 2);
        if ($result) {
            return okBack('发送成功');
        } else {
            return errBack('发送失败');
        }
    }
}
